package cn.zs.supply.common.core.security.simple;

import cn.zs.supply.common.constants.enums.MsgDataEnum;
import cn.zs.supply.common.constants.enums.PubErrCode;
import cn.zs.supply.common.core.login.LoginContext;
import cn.zs.supply.common.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**登录成功
 */
@Component
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private RsaSigner signer;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${application.type}")
    private String LongType;
    @Value("${login.time}")
    private Long time;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String userJsonStr = JSON.toJSONString(authentication.getPrincipal());
        JSONObject json=JSONObject.parseObject(userJsonStr);
        String username=json.get("username").toString();
        String token = JwtHelper.encode(userJsonStr, signer).getEncoded();
        System.setProperty(MsgDataEnum.FEIGN_TOKEN.getCode(), token);
        Object object = LoginContext.get().getObject();
        //System.out.println(JSON.toJSONString(object));
        redisTemplate.opsForValue().set(LongType+username, token, time, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(object), time, TimeUnit.SECONDS);
        //签发token
        //response.getWriter().write("token="+token);
        JSONObject responseJson=new JSONObject();
        responseJson.put("token",token);
        responseJson.put("code", PubErrCode.SUCCESS_LOGINED.getCode());
        responseJson.put("errcode",PubErrCode.SUCCESS_LOGINED.getCode());
        responseJson.put("msg",PubErrCode.SUCCESS_LOGINED.getMsg());
        responseJson.put("success", "true");
        ResponseUtil.setResponse(response,responseJson);
    }
    public void setSigner(RsaSigner signer) {
        this.signer = signer;
    }
}
